import {Command, GAME_TYPE, PROP_STAUTS, GAME_RPICE_TYPE, TASK_CONDITION_TYPE} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import api from 'api';
import {extraPathsValue} from '@/redux/util';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    /**
     * 查询用户信息
     * isAquamarineMember-蓝晶会员 
     * isCrystalMember-赤晶会员
     */
    async loadUserInfo() {
      let res = await api.customerBaseController.findCustomerBaseInfo();
      action.commonChange('main.isAquamarineMember', res.isAquamarineMember);
      action.commonChange('main.isCrystalMember', res.isCrystalMember);
      Taro.setStorageSync('gameUserInfo', res);
      // 会员则先去获取每日赠送的游戏次数
      if (res.isAquamarineMember || res.isCrystalMember) {
        let dailyResult = action.loadGameTimesReceiveDaily({delFlag: null});
        return dailyResult;
      } else {
        action.loadGameTimes();
        return 'loadGameTimes';
      }
    },

    /**
     * 查询每日游戏次数领取，收下or拒绝
     * @param payload
     */
    async loadGameTimesReceiveDaily(payload) {
      // 编辑参数
      let params = {
        gameType: GAME_TYPE,
        ...payload,
      };

      let {data, code, message} = await api.GoldCoinsController.getGameTimesReceiveDaily(params);

      let result = data
        ? {
            ...payload,
            ...data,
          }
        : {
            ...payload,
          };

      // 无信息则弹出开心收下弹框
      if (!result.id) {
        action.hideCanvas();
        action.commonChange('main.showDailyExclusiveModal', true);
      } else {
        action.loadGameTimes();
      }
      return 'ReceiveDaily'
    },

    /**
     * 查询任务列表
     */
    async loadTaskItems(payload) {
      action.commonChange('main.response.loadTask', '');
      action.commonChange('main.status.loadingTask', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE, // 暂时
      };
      let {data, code, message} = await api.GameTaskController.getTasksByGameType(params);
      console.log('loadTaskItems action data', data);

      let {
        main: {task},
      } = getData();

      action.commonChange('main.task', {
        ...task,
        items: data || [],
        page: {
          ...task.page,
        },
      });

      action.commonChange('main.response.loadTask', code);
      action.commonChange('main.status.loadingTask', false);
    },

    /**
     * 查询任务详情
     */
    async loadTaskDetailById(payload) {
      action.commonChange('main.response.loadTaskDetail', '');
      action.commonChange('main.status.loadingTaskDetail', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, code, message} = await api.GameTaskController.getTaskDetailById(params);
      console.log('loadTaskItems action data', data);

      let {
        main: {task},
      } = getData();

      action.commonChange('main.task', {
        ...task,
        detail: {
          ...(data || {}),
        },
      });
      action.commonChange('main.response.loadTaskDetail', code);
      action.commonChange('main.status.loadingTaskDetail', false);
    },

    /**
     * 查询游戏可玩次数
     */
    async loadGameTimes() {
      let {data, code, message} = await api.iplandBaseController.getGameTimesConfigInfo({gameType: 5});
      action.commonChange('main.gameTimes', data);
    },

    /**
     * 查询当日游戏剩余可玩次数
     */
    async loadGameDailyLeftTimes() {
      // 编辑参数
      let payload = {
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.iplandBaseController.getGameDailyTimes(payload);
      console.log('goldCoinsIndex loadGameDailyTimes data', data);
      action.commonChange('main.gameDailyLeftTimes', data);
    },

    /**
     * 查询游戏信息
     * @param payload
     */
    async loadGameInfo() {
      action.commonChange('main.gameInfo', {});

      //0-魔力金币雨，1-魔力抽盲盒，2-魔力赏，3-魔力抓娃娃，4-魔力抽抽卡，5-刮刮乐
      let {data, code, message} = await api.GoldCoinsController.getGameIpConfigInfo({gameType: 5});
      console.log('action.ts loadGameInfo data', data);
      data = data || {};

      let gameInfo = {};
      gameInfo = {
        ...data,
        text: data.detail ? data.detail : '',
      };

      action.commonChange('main.gameInfo', gameInfo);
    },

    /**
     * 查询道具信息
     */
    async loadPropItems(payload) {
      action.commonChange('main.response.loadProp', '');
      action.commonChange('main.status.loadingProp', true);

      // 编辑参数
      let params = {
        // ...payload,
        prizeType: GAME_RPICE_TYPE['prop'],
        status: PROP_STAUTS['UNUSE'],
      };

      let {data, code, message} = await api.GamePropController.getMyProp(params);
      console.log('action.ts loadProp data', data);
      data = data || [];

      // 重组数据
      let result = [];
      if (data.length > 0) {
        data.map((i) => {
          i.propVO = i.propVO || {};
          result.push({
            ...i,
            propImg: i.propVO.imgUrl,
            propName: i.propVO.propName,
            propEndTime: i.propVO.endTime,
            propDesc: i.propVO.propDesc,
            propStartTime: i.propVO.startTime,
          });
        });
      }

      let {
        main: {prop},
      } = getData();

      action.commonChange('main.prop', {
        ...prop,
        items: result || [],
        page: {
          ...prop.page,
        },
      });
      action.commonChange('main.response.loadProp', code);
      action.commonChange('main.status.loadingProp', false);
    },

    /**
     * 判断能否使用道具
     * @param payload
     */
    async usePropPossibility(payload) {
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.response.usePropPossibility', '');
      action.commonChange('main.status.usingPropPossibility', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.GamePropController.useProp(params);
      console.log('action.ts usePropPossibility data', data);

      action.commonChange('main.response.usePropPossibility', code);
      action.commonChange('main.codeMessage', message);
      action.commonChange('main.status.usingPropPossibility', false);
    },

    /**
     * 查询新人保障
     */
    async loadUserIsNewComer() {
      action.commonChange('main.response.isNewComer', '');

      let params = {
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.CatchPlaythingController.userIsNewComer(params);
      console.log('action.ts loadUserIsNewComer data', data);

      action.commonChange('main.isNewComer', data);
    },

    /**
     * 奖品抽奖
     */
    async gameLottery(payload) {
      Taro.showLoading();
      action.commonChange('main.gameLotteries', []);
      action.commonChange('main.response.loadGameLottery', '');
      action.commonChange('main.status.loadingGameLottery', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      // 编辑参数
      let {data, code, message} = await api.iplandBaseController.gameScratch(params);
      console.log('action.ts gameLottery res', data);
      if (code != 'K-000000') {
        Taro.showToast({
          title: message,
          icon: 'none',
          duration: 2000,
        });
        return;
      }

      //0-商品 1-优惠券 2-魔力币 3-道具 4-卡片 (卡片平铺，其他都统计)
      // 统计信息 （商品平铺，安慰奖统计）
      data = data || [];
      let result = data.filter(
        (i) =>
          i.prizeType != null &&
          i.prizeType != GAME_RPICE_TYPE['ticket'] &&
          i.prizeType != GAME_RPICE_TYPE['gold'] &&
          i.prizeType != GAME_RPICE_TYPE['prop'],
      );

      if (data && data.length > 0) {
        // 优惠券筛选
        let tickItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['ticket']);
        if (tickItems.length > 0) {
          result.push({
            id: tickItems.length,
            prizeType: GAME_RPICE_TYPE['ticket'],
            count: tickItems.length,
          });
        }

        // 道具
        let propItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['prop']);
        if (propItems.length > 0) {
          result.push({
            id: propItems.length,
            prizeType: GAME_RPICE_TYPE['prop'],
            count: propItems.length,
          });
        }

        // 金币筛选
        let goldItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['gold']);
        let goldNum = goldItems.reduce((goldNum, currentItem) => {
          currentItem.magicCoin = currentItem.magicCoin || 0;
          return goldNum + currentItem.magicCoin;
        }, 0);

        if (goldItems.length > 0) {
          result.push({
            id: result.length + 1,
            prizeType: GAME_RPICE_TYPE['gold'],
            count: goldNum,
          });
        }
      }
      action.commonChange('main.gameLotteries', result || []);
      // action.commonChange('main.getPrize', result.length > 0);
      action.commonChange('main.response.loadGameLottery', code);
      action.commonChange('main.status.loadingGameLottery', false);

      Taro.hideLoading();
      action.gameOver();

      // 如果使用了道具后更新道具列表
      if (payload.propId) {
        action.loadPropItems({});
      }
    },

    // 游戏结束
    gameOver() {
      action.hideCanvas();
      action.commonChange('main.showGameOverModal', true);
      // 更新底部游戏次数
      action.loadGameTimes();
      // 获取每日剩余游戏次数
      action.loadGameDailyLeftTimes();
      // 玩过游戏之后不再是新人
      action.commonChange('main.isNewComer', false);
    },

    hideCanvas() {
      action.commonChange('main.showCanvas', false);
      // action.commonChange('main.showAwardTxt', false);
    },

    /**
     * 批量领取奖励 （针对抓娃娃结果页领取奖励的跳转）
     */
    async claimRewards(payload) {
      action.commonChange('main.response.claimRewards', '');
      action.commonChange('main.status.claimingRewards', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      // 编辑参数
      let {data, code, message} = await api.CatchPlaythingController.claimRewards(params);
      console.log('action.ts loadGameLottery res', data);

      action.commonChange('main.response.claimRewards', code);
      action.commonChange('main.status.claimingRewards', false);
    },

    /**
     * 完成任务
     * @param payload
     */
    async computedTask(payload) {
      // 编辑参数
      let params = {
        ...payload,
      };
      let {data, code, message} = await api.GameTaskController.computedTask(params);
      if (payload.taskConditionsType == TASK_CONDITION_TYPE['game']) {
        if (code == 'K-000000') {
          Taro.showToast({
            title: '任务完成！',
          });

          // 完成任务后刷新任务列表
          action.loadTaskItems({});
          Taro.removeStorageSync('scratch_task_query');
        } else {
          Taro.showToast({
            title: '任务失败！',
          });
        }
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageIScratchMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
